Categories:

Creating an attractive Hover Menu using CSS & JavaScript

As CSS matures, and so too web browsers in supporting it, the concept behind hover menu effects is being redefined. Pretty much gone are JavaScript based image rollover effects, replaced with something far leaner and easier to mantain, using CSS. However, one technology will never fully replace the other, and in this article, I'll show you how to create a nice CSS based menu, then enhance it further with JavaScript.

CSS hover menu

Below is a 100% CSS based hover menu. The source code for it follows.

Example:

Source:

<style type="text/css">

#coolmenu{
border: 1px solid black;
width: 170px;
background-color: #E6E6E6;
}

#coolmenu a{
font: bold 13px Verdana;
padding: 2px;
padding-left: 4px;
display: block;
width: 100%;
color: black;
text-decoration: none;
border-bottom: 1px solid black;
}

html>body #coolmenu a{ /*Non IE rule*/
width: auto;
}

#coolmenu a:hover{
background-color: black;
color: white;
}

</style>

<div id="coolmenu">
<a href="http://www.javascriptkit.com">JavaScript Kit</a>
<a href="http://www.javascriptkit.com/cutpastejava.shtml">Free JavaScripts</a>
<a href="http://www.javascriptkit.com/jsref/">JavaScript Reference</a>
<a href="http://www.codingforums.com">Coding Forums</a>
<a href="http://www.dynamicdrive.com">Dynamic Drive</a>
</div>

The key here is to set each <a> element to have a "display: block" inside the CSS. This transforms each <a> to a block element, and react as such when the mouse hovers over it.

Ok, lets move on now to see how to use Javascript to "improve" the menu, by showing a description of each menu item onMouseover.